<?php


//http://app.5b245.com

namespace app\api\controller;

use app\api\model\Index as ApiModel;
use think\Request;
use Db;

class Index
{

    /***
     * 获取首页数据
     * @param  lng  经度
     * @param  lat  纬度
     */
    public function getHomePage(Request $request)
    {

        $lng = $request->param('lng'); //经度
        $lat = $request->param('lat'); //纬度

        //海报图
        $poster_img = Db::name('system_settings')->limit(1)->cache(30)->value('poster_img');

        //特色二手房模块
        $resold_types = Db::name('house_module')
                         ->field('id module_id,title,intro,thumb_img img')
                         ->where(['type'=>2,'off'=>1])->limit(3)->cache(20)->select();

        //推荐新盘模块
        $new_types = Db::name('house_module')
                    ->field('id module_id,title,intro,thumb_img img')
                    ->where(['type'=>1,'off'=>1])->limit(3)->cache(20)->select();

        //猜你喜欢模块
        if ($lng && $lat) {

//            根据坐标排序
//            $rows = Db::query('select * from new_house order by ACOS(SIN(('.$lat.' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$lat.' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS(('.$lng.' * 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380  asc  limit 30');


            $guess_house_list = Db::name('new_house')
                                ->field('id house_id,thumb_img,title,intro,min_area,max_area,unit_price,labels')
                                ->where('off',1)
                                ->orderRaw('ACOS(SIN(('.$lat.' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$lat.' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS(('.$lng.' * 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc')
                                ->limit(20)->cache(10)->select();

            $nearby= Db::name('new_house')
                ->field('uptown,lng,lat,unit_price,on_sale_num')
                ->where('off',1)
                ->orderRaw('ACOS(SIN(('.$lat.' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$lat.' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS(('.$lng.' * 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc')
                ->cache(20)->find();



        }else{

            $guess_house_list = Db::name('new_house')
                                ->field('id house_id,thumb_img,title,intro,min_area,max_area,unit_price,labels')
                                ->where('off',1)->order('id','desc')->limit(20)->cache(10)->select();
        }


        if ($guess_house_list) {

            foreach($guess_house_list as &$v){
                unset($v['uptown']);
                //标签
                $v['labels']  = Db::name('house_label')->field('tag_name,color_type')->whereIn('id',$v['labels'])->cache(20)->select();
            }
        }


        if(empty($nearby)){
            $nearby = ['house_name'=>'暂无信息','unit_price'=>'暂无均价','for_sale'=>0,'distance'=>0];

        }else{
            $nearby = [
                'house_name'=>$nearby['uptown'],
                'unit_price'=>$nearby['unit_price'].'元/m²',
                'for_sale'=>$nearby['on_sale_num'],
                'distance'=>get_distance([$lng,$lat],[$nearby['lng'],$nearby['lat']])
            ];

        }

        $res  = array(
            'img_prefix'          => config('api.oss_img_path'),
            'poster_img'          => $poster_img,
            'resold_house_module' => $resold_types,
            'new_house_module'    => $new_types,
            'guess_house_list'    => $guess_house_list,
            'nearby_house'        => $nearby
        );

        return msg(200,'success',$res);
    }



    /**
     * 获取房源搜索选项
     * @param adcode         行政区编码 (海外的为国家的id)
     * @param option_type    选项类型 1新盘 2二手房 3出租房 4家居 5装修  6海外
     */
    public function getSeachOption(Request $request) {

        $adcode     = $request->param('adcode');
        $option_type = $request->param('option_type');

        if(!$adcode) return msg(101,'参数有误');
        if(!$option_type) return msg(101,'参数有误');


        if($option_type<6){
            //国内区域
            $region = Db::name('region')->field('id adcode,shortname')->where("pid = (select pid from region where id = $adcode)")->cache(20)->select();

            if($region){
                foreach($region as $k=>&$v){
                    $v['place_list'] =Db::name('region')->field('id place_code,shortname place_name')->where('pid',$v['adcode'])->cache(20)->select();
                    array_unshift($v['place_list'],['place_code'=>0,'place_name'=>'全部']);
                }
            }

        }else{
            //海外区域
            $region = Db::name('overseas_region')->field('id adcode,shortname')->where('pid',$adcode)->select();
        }

        $res = array(
            'city_region' => $region,    //区域
        );
        $imgPath = config('api.oss_img_path');
        switch ($option_type) {
            case 1:
                $label  =  Db::name('house_label')->field('id tag_id,tag_name')->where('type',1)->cache(10)->select();   //标签
                $res['poster_img'] = $imgPath.Db::name('house_module')->where('type',4)->cache(20)->value('poster_img');
                $res['price_range'] = config('api.price_range');   //价格区间
                $res['area_range'] = config('api.area_range');    //面积范围
                $res['house_types'] = config('api.house_types');   //房型
                $res['purpose']     = config('api.purpose');       //用途
                $res['labels'] = $label;
                $res['sell_case'] = config('api.sell_case');
                $res['house_open_time'] = config('api.house_open_time');

                break;

            case 2:

                $label  =  Db::name('house_label')->field('id tag_id,tag_name')->where('type',2)->cache(10)->select();   //标签
                $res['poster_img'] = $imgPath.Db::name('house_module')->where('type',3)->cache(20)->value('poster_img');
                $res['price_range'] = config('api.price_range');   //价格区间
                $res['area_range'] = config('api.area_range');    //面积范围
                $res['house_types'] = config('api.house_types');   //房型
                $res['purpose']     = config('api.purpose');       //用途
                $res['aspect']      = config('api.aspect');        //朝向
                $res['floor_types'] = config('api.floor_types');   //楼层
                $res['labels']      = $label;                      //标签

                break;

            case 3:
                $label  =  Db::name('house_label')->field('id tag_id,tag_name')->where('type',3)->cache(10)->select();   //标签
                $res['poster_img'] = $imgPath.Db::name('house_module')->where('type',5)->cache(20)->value('poster_img');
                $res['rent_types']  = config('api.rent_types');
                $res['area_range'] = config('api.area_range');    //面积范围
                $res['price_range'] = config('api.rent_price_range');   //价格区间
                $res['house_age_range'] = config('api.house_age_range');   //楼龄区间
                $res['fitment_case'] = config('api.fitment_case');   //楼龄区间
                $res['labels']      = $label;                           //标签
                foreach($res['house_age_range'] as &$v){
                    unset($v['min']);
                    unset($v['max']);
                }
                break;

            case 4:
                $res['poster_img'] = $imgPath.Db::name('house_module')->where('type',6)->cache(20)->value('poster_img');
                $res['attrs'] = config('api.furniture_store_attrs');
                $res['price_range'] = config('api.furniture_store_price_range');

                break;
            case 5:
                $res['poster_img'] = $imgPath.Db::name('house_module')->where('type',7)->cache(20)->value('poster_img');
                $res['attrs'] = config('api.fitment_store_attrs');
                $res['price_range'] = config('api.fitment_store_price_range');

                break;
            case 6:

                $label  =  Db::name('house_label')->field('id tag_id,tag_name')->where('type',2)->cache(10)->select();  //标签
//                $res['poster_img'] = $imgPath.Db::name('house_module')->where('type',8)->cache(20)->value('poster_img');
                $res['price_range'] = config('api.price_range');   //价格区间
                $res['area_range'] = config('api.area_range');    //面积范围
                $res['house_types'] = config('api.house_types');   //房型
                $res['purpose']     = config('api.purpose');       //用途
                $res['aspect']      = config('api.aspect');        //朝向
                $res['floor_types'] = config('api.floor_types');   //楼层
                $res['labels']      = $label;                      //标签

                break;

        }


        if(!empty($res['price_range'])){
            foreach($res['price_range'] as &$v){
                unset($v['min']);
                unset($v['max']);
            }
        }
        if(!empty($res['area_range'])){
            foreach($res['area_range'] as &$v){
                unset($v['min']);
                unset($v['max']);
            }
        }

        return msg(200,'success',$res);
    }




    /**
     * 获取片区地点
     * @param adcode  行政区编码
     */
    public function getPlaceRegion(Request $request)
    {

        $adcode = $request->param('adcode');

        if($adcode){

            $res = Db::name('region')->field('id place_code,name place_name')->where('pid',$adcode)->cache(20)->select();

            return msg(200,'success',$res);
        }else{
            return msg(101,'缺少adcode');

        }
    }


    /**
     * 获取二手房房源
     * @param lng           经度
     * @param lat           纬度
     * @param module_id     模块id
     * @param page          页码
     * @param adcode        行政区编码 （区域id）
     * @param place_code    地方编码
     * @param price_type    价格类型
     * @param house_type    房型
     * @param area_type     面积类型
     * @param aspect_id     朝向标记
     * @param floor_type    楼层类型
     * @param purpose_id    用途标记
     * @param tag_ids       标签ids
     * @param seach_text    搜索内容
     * @param min_price     最低价格
     * @param max_price     最高价格
     */
    public function getResoldHouse(Request $request){

        $inputData   = $request->param();

//        if(empty($inputData['lng']) || empty($inputData['lat'])){
//            return msg(101,'请上传坐标');
//        }

//        $lng         = $request->param('lng')?:114.42311;
//        $lat         = $request->param('lat')?:23.085747;

        $lng         = $request->param('lng');
        $lat         = $request->param('lat');

        if(empty($lng) || empty($lat)){
            return msg(101,'请上传坐标');
        }

        $page        = $request->param('page')?:1;
        $pageSize    = 15;
        $start       = ($page-1)*$pageSize;

        $where       = [];

        //模块条件
        if(!empty($inputData['module_id'])){

            switch ($inputData['module_id']){
                case 1:
                    $where[] = ['room_num','>',2] ;
                    break;

                case 2:
                    $where[] = ['room_num','<',3] ;
                    break;

                case 3:
//                    $where[] = ['room_num','>',2] ;
                    break;
            }
//            $where[] = ['module_id','=',$inputData['module_id']] ;
        }

        //区域条件
        if(!empty($inputData['place_code'])) {
            //片区
           $where[] =  ['area_id', '=',$inputData['place_code']];

        }else if(!empty($inputData['adcode'])){

            //行政区
            $pids = Db::name('region')->field('id')->where('pid',$inputData['adcode'])->cache(20)->select();

//            $where[] = ['area_id','in',"select id from region where pid ={$inputData['adcode']}"];
            if($pids){
                $ids = '';
                foreach($pids as $v){
                   $ids .= ','.$v['id'];
                }

                $ids = ltrim($ids,',');

                $where[]=['area_id','in',$ids];
            }

        }



        //价格区间
        if( !empty($inputData['min_price']) ){
            $where[] = ['total_price', '>=', $inputData['min_price']];


        }elseif(!empty($inputData['max_price'])){
            $where[] = ['total_price', '<=', $inputData['max_price']];

        }else {
            //价格区间
            if (!empty($inputData['price_type'])) {

                $price_range = config('api.price_range')[$inputData['price_type'] - 1];

                $where[] = ['total_price', '>=', $price_range['min']];
                if ($price_range['max'] > 0) {
                    $where[] = ['total_price', '<=', $price_range['max']];
                }
            }
        }

        //面积区间
        if(!empty($inputData['area_type'])){

            $area_range = config('api.area_range')[$inputData['area_type']-1];

            $where[] = ['total_area','>=',$area_range['min']] ;
            if($area_range['max']>0){
                $where[] = ['total_area','<=',$area_range['max']] ;
            }
        }

        if(!empty($inputData['house_type']))  $where[] = ['room_num','in',$inputData['house_type']] ;    //房型



        if(!empty($inputData['aspect_id']))   $where[] = ['direction','=',$inputData['aspect_id']] ;    //朝向

        if(!empty($inputData['floor_type']))  $where[] = ['floor_type','=',$inputData['floor_type']] ;  //楼层类型

        if(!empty($inputData['purpose_id']))  $where[] = ['use_type','=',$inputData['purpose_id']] ;    //用途


        $where2 = 'off=1';
        if(!empty($inputData['tag_ids'])) {
            //标签
            $tags = explode(',',$inputData['tag_ids']);

            if($tags){
                $where2 .=' and (';
                foreach($tags as $v) {
                    $where2 .= " FIND_IN_SET($v,labels) or";
                }
                $where2 = rtrim($where2,'or').')';
            }
        }



        if(!empty($inputData['seach_text'])) {
            $data = Db::name('resold_house')->field('id house_id,title,thumb_img,labels,total_area,direction,floor_type,floors,total_price,unit_price')
                ->where('title|address|uptown','like',"%{$inputData['seach_text']}%")
                ->where('off',1)
                ->orderRaw('ACOS(SIN(('.$lat.' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$lat.' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS(('.$lng.' * 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc')
                ->limit($start,$pageSize)->cache(20)->select();
        }else{
            $data = Db::name('resold_house')->field('id house_id,title,thumb_img,labels,total_area,direction,floor_type,floors,total_price,unit_price')
                ->where($where)->where($where2)
                ->orderRaw('ACOS(SIN(('.$lat.' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$lat.' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS(('.$lng.' * 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc')
                ->limit($start,$pageSize)->cache(20)->select();
        }


        if($data){
            foreach($data as &$row){
                $row['direction'] = config('api.aspect')[$row['direction']-1]['aspect_name'];
                $row['floor_type'] = ApiModel::$floor_types[$row['floor_type']];
                $row['labels']  = Db::name('house_label')->field('tag_name,color_type')->whereIn('id',$row['labels'])->cache(20)->select();
                $row['intro'] = $row['total_area'].'m²/'.$row['direction'].'/'.$row['floor_type'].'/共'.$row['floors'].'层';
            }
        }

        $res['img_prefix']  = config('api.oss_img_path');
        $res['house_list']  = $data;
        $res['next_page']   = $page+1;

        return msg(200,'success',$res);

    }


    /**
     * 获取二手房详情
     * @param  house_id  房源id
     * @param  app_uuid  手机唯一标识
     * @param  uid
     */
    public function getResoldHouseDetails(Request $request){

        $house_id = $request->param('house_id');
        $app_uuid = $request->param('app_uuid');

        if(!$house_id || !$app_uuid) return msg(101,'参数有误');

        $details = Db::name('resold_house a')
                   ->join('house_broker b','a.broker_id=b.id','left')
                   ->field('a.title,a.description,a.labels,a.total_area,a.total_price,a.direction,a.floor_type,a.floors,a.unit_price,a.address,a.uptown,a.viewpager,a.durable_years,a.coding,a.budget,a.usable_area,a.structure,a.floor_ratio,a.heating,a.transaction_type,a.property_right_type,a.pledge,a.house_cert,a.soil_years,a.lng,a.lat,a.time,a.room_num,a.lobby_num,a.carport_type,a.use_type,a.fitment_case,a.broker_id,b.broker_phone,b.broker_name,b.hx_username broker_hx_name,b.avatar broker_avatar')
                   ->where('a.id',$house_id)->where('a.off',1)->cache(20)->find();

        if($details){

            $details['img_prefix'] =  config('api.oss_img_path');

            $details['viewpager']  =  json_decode($details['viewpager'],true);

            $config = config('api.numberToChinese');

            $details['direction'] = config('api.aspect')[$details['direction']-1]['aspect_name'];

            $details['house_type'] =  $config[$details['room_num']].'房'.$config[$details['lobby_num']].'厅';

            $details['structure'] =  $details['structure']?:'暂无信息';

            $details['heating']  =config('api.heating')[$details['heating']];

            $details['house_cert']  = $details['house_cert']?:'';

            $details['carport_type']  = config('api.carport_types')[ $details['carport_type']];

            $details['floor_ratio'] = '一梯'.config('api.numberToChinese')[$details['floor_ratio']].'户';
            $details['labels'] =  Db::name('house_label')->field('tag_name,color_type')->whereIn('id',$details['labels'])->cache(20)->select();

            $details['floor_type'] = config('api.floor_types')[$details['floor_type']-1]['title'];

            $details['use_type'] = config('api.purpose')[$details['use_type']-1]['title'];

            $details['fitment_case']  = config('api.fitment_case')[$details['fitment_case']-1]['title'];

            $details['transaction_type']  = config('api.transaction_types')[$details['transaction_type']];

            $details['property_right_type']  = config('api.property_right_types')[$details['property_right_type']];

            $details['lately_deal'] = '暂无数据';

            $details['intro'] = $details['total_price'].'万/'.$details['total_area'].'m²/'.$details['house_type'];

            $details['nearby_house'] = Db::name('resold_house')->field('id house_id,title,thumb_img,total_price,unit_price')
                ->where('off',1)
                ->orderRaw('ACOS(SIN(('.$details['lat'].' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$details['lat'].' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS(('.$details['lng'].' * 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc')
                ->limit(5)->cache(20)->select();
            unset($details['room_num']);
            unset($details['lobby_num']);
            $uid = $request->param('uid');


            //关注状态
            if(empty($uid)){
                $details['collect_status'] = 2;

            }else{

                $coll = Db::name('app_user_collect')->where(['uid'=>$uid,'house_id'=>$house_id,'type'=>2])->find();

                $details['collect_status'] = empty($coll)?2:1;

            }


            //保存记录
            ApiModel::saveRecord($app_uuid,$house_id,2);


            return msg(200,'success',$details);

        }else{
            return msg(100,'暂无数据');

        }

    }


    /**
     * 获取新房
     * @param lng           经度
     * @param lat           纬度
     * @param module_id     模块id
     * @param page          页码
     * @param adcode        行政区编码 （区域id）
     * @param place_code    地方编码
     * @param price_type    价格类型
     * @param house_type    房型
     * @param area_type     面积类型
     * @param purpose_id    用途标记
     * @param tag_ids       标签ids
     * @param sell_state    售卖状态
     * @param time_type     开盘时间（标记）
     * @param seach_text    搜索内容
     * @param min_price    最低价格
     * @param max_price    最高价格
     */
    public function getNewHouse(Request $request){

        $inputData   = $request->param();

        $lng         = $request->param('lng')?:114.42311;

        $lat         = $request->param('lat')?:23.085747;

        $page        = $request->param('page')?:1;
        $pageSize    = 15;
        $start       = ($page-1)*$pageSize;

        $where       = [];

        //模块条件
        if(!empty($inputData['module_id'])) $where[] = ['module_id','=',$inputData['module_id']] ;

        //区域条件
        if(!empty($inputData['place_code'])) {
            //片区
            $where[] =  ['area_id', '=',$inputData['place_code']];

        }else if(!empty($inputData['adcode'])){

            //行政区
            $pids = Db::name('region')->field('id')->where('pid',$inputData['adcode'])->cache(20)->select();

//            $where[] = ['area_id','in',"select id from region where pid ={$inputData['adcode']}"];
            if($pids){
                $ids = '';
                foreach($pids as $v){
                    $ids .= ','.$v['id'];
                }

                $ids = ltrim($ids,',');

                $where[]=['area_id','in',$ids];
            }

        }

        $where2 = 'off=1';

        //价格区间
        if( !empty($inputData['min_price']) ){

            $where2 .= ' and unit_price * min_area <= '.$inputData['min_price']*10000;  //最低价格

        }elseif(!empty($inputData['max_price'])){
            $where2 .= ' and unit_price * min_area >= '.$inputData['max_price']*10000;  //最高价格

        }else{

            if((!empty($inputData['price_type']))){
                $price_range = config('api.price_range')[ $inputData['price_type']-1 ];
                $where2 .= ' and unit_price * min_area <= '.$price_range['min']*10000;  //最低价格

                if($price_range['max']>0){
                    $where2 .= ' and unit_price * max_area >= '.$price_range['max']*10000; //最高价格

                }
            }

//
        }



        //面积区间
        if(!empty($inputData['area_type'])){

            $area_range = config('api.area_range')[$inputData['area_type']-1];

            $where[] = ['min_area','<=',$area_range['min']] ;
            if($area_range['max']>0){
                $where[] = ['max_area','>=',$area_range['max']] ;
            }
        }

        if(!empty($inputData['purpose_id']))  $where[] = ['use_type','=',$inputData['purpose_id']] ;    //用途

        //售卖状态
        if(!empty($inputData['sell_state'])) {
            if($inputData['sell_state'] == 3) {
                $where[] = ['open_time','>',time()]; //未开盘
            }else{
                $where[] = ['sell_state','=',$inputData['sell_state']] ;
            }
        }

        if(!empty($inputData['time_type'])) {
            switch ($inputData['time_type']) {
                case 1:
                    $where2 .= ' and open_time BETWEEN '.time().' AND '.strtotime('+1 month');
                    break;
                case 2:
                    $where2 .= ' and open_time BETWEEN '.strtotime('+1 month').' AND '.strtotime('+2 month');
                    break;
                case 3:
                    $where2 .= ' and open_time BETWEEN '.strtotime('+3 month').' AND '.strtotime('+4 month');
                    break;
                case 4:
                    $where2 .= ' and open_time BETWEEN '.strtotime('+6 month').' AND '.strtotime('+7 month');
                    break;
                case 5:
                    $where2 .= ' and open_time BETWEEN '.strtotime('-1 month').' AND '.time();
                    break;
                case 6:
                    $where2 .= ' and open_time BETWEEN '.strtotime('-3 month').' AND '.strtotime('-1 month');
                    break;
            }
        }


        if(!empty($inputData['tag_ids'])) {
            //标签
            $tags = explode(',',$inputData['tag_ids']);

            if($tags){
                $where2 .=' and (';
                foreach($tags as $v) {
                    $where2 .= " FIND_IN_SET($v,labels) or";
                }
                $where2 = rtrim($where2,'or').')';
            }
        }


        $where3 = 1;
        if(!empty($inputData['house_type'])){
            //房型
            $types = explode(',',$inputData['house_type']);

            if($types){
                $where3 .=' and (';
                foreach($types as $v) {
                    $where3 .= " FIND_IN_SET($v,labels) or";
                }
                $where3 = rtrim($where3,'or').')';
            }
        }


        if(!empty($inputData['seach_text'])){
            //搜索
            $data = Db::name('new_house')->field('id house_id,title,intro,thumb_img,labels,min_area,max_area,unit_price,coupon_id coupon')
                ->where('off',1)
                ->where('title|address|uptown','like',"%{$inputData['seach_text']}%")
                ->orderRaw('ACOS(SIN(('.$lat.' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$lat.' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS(('.$lng.' * 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc')
                ->limit($start,$pageSize)->cache(20)->select();
        }else{

            $data = Db::name('new_house')->field('id house_id,title,intro,thumb_img,labels,min_area,max_area,unit_price,coupon_id coupon')
                ->where($where)->where($where2)->where($where3)
                ->orderRaw('ACOS(SIN(('.$lat.' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$lat.' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS(('.$lng.' * 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc')
                ->limit($start,$pageSize)->cache(20)->select();
        }



        if($data){
            foreach($data as &$row){
                $row['labels']  = Db::name('house_label')->field('tag_name,color_type')->whereIn('id',$row['labels'])->cache(20)->select();
                if($row['coupon']>0){
                    $row['coupon'] = Db::name('house_coupon')->where(['id'=>$row['coupon'],'off'=>1])->cache(20)->value('coupon_name')?:'';
                }else{
                    $row['coupon']='';
                }
            }
        }

        $res['img_prefix']  = config('api.oss_img_path');
        $res['house_list']  = $data;
        $res['next_page']   = $page+1;

        return msg(200,'success',$res);

    }


    /**
     * 获取新楼盘详情
     * @param  house_id  房源id
     * @param  app_uuid  手机唯一标识
     * @param  uid
     */
    public function getNewHouseDetails(Request $request){


        $house_id = $request->param('house_id');
        $app_uuid = $request->param('app_uuid');
        $uid = $request->param('uid');

        if(!$house_id || !$app_uuid) return msg(101,'参数有误');

        $details = Db::name('new_house a')
            ->join('house_broker b','a.broker_id=b.id','left')
            ->field('a.title,a.viewpager,a.labels,a.unit_price,a.new_houses_time,a.update_time,a.address,a.open_time,a.developers,a.min_area,a.max_area,a.check_out_time,a.durable_years,a.exequatur,a.house_types,a.lng,a.lat,a.coupon_id coupon,a.broker_id,b.broker_phone,b.broker_name,b.hx_username broker_hx_name,b.avatar broker_avatar')
            ->where('a.id',$house_id)->where('a.off',1)->cache(20)->find();
        if($details){


            $details['img_prefix'] =  config('api.oss_img_path');
            $details['labels'] =  Db::name('house_label')->field('tag_name,color_type')->whereIn('id',$details['labels'])->cache(20)->select();

            $details['viewpager']  =  json_decode($details['viewpager'],true);
            $details['house_types']  =  json_decode($details['house_types'],true);

            $details['new_houses_time'] = date('Y年m月d日',$details['new_houses_time']);
            $details['open_time'] = date('Y年m月d日',$details['open_time']);
            $details['check_out_time'] = date('Y年m月d日',$details['check_out_time']);
            $details['update_time'] = date('Y年m月d日',$details['update_time']);

            if($details['coupon']>0){
                $coupon = Db::name('house_coupon')->where(['id'=>$details['coupon'],'off'=>1])->value('coupon_name');
                if($coupon){
                    $details['coupon'] = array('coupon_id'=>$details['coupon'],'coupon_name'=>$coupon);
                }else{
                    $details['coupon'] = (object)[];

                }

            }else{
                $details['coupon'] = (object)[];
            }

            $config = config('api.numberToChinese');


            $details['broker_phone'] =  $details['broker_phone']?:'';
            $details['intro'] = $details['unit_price'].'元/m² '.$details['min_area'].'-'.$details['max_area'].'m²';


            $details['nearby_house'] = Db::name('new_house')->field('id house_id,title,intro,thumb_img,labels,min_area,max_area,unit_price')
                ->where('off',1)
                ->orderRaw('ACOS(SIN(('.$details['lat'].' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$details['lat'].' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS(('.$details['lng'].' * 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc')
                ->limit(5)->cache(20)->select();




            if(!empty($details['nearby_house'])){

                foreach($details['nearby_house'] as &$row) {
                   $row['labels'] = Db::name('house_label')->field('tag_name,color_type')->whereIn('id', $row['labels'])->cache(20)->select();

                }

            }



            //关注状态
            if(empty($uid)){
                $details['collect_status'] = 2;

            }else{

                $coll = Db::name('app_user_collect')->where(['uid'=>$uid,'house_id'=>$house_id,'type'=>1])->find();

                $details['collect_status'] = empty($coll)?2:1;

            }



            unset($details['lng']);
            unset($details['lat']);

            //保存记录
            ApiModel::saveRecord($app_uuid,$house_id,1);

            return msg(200,'success',$details);

        }else{
            return msg(200,'暂无数据');

        }

    }

    /**
     * 获取新楼盘推荐页列表
     * @param lng 经度
     * @param lat 维度
     */
    public function getNewHouseRecommend (Request $request) {


        $lng         = $request->param('lng')?:114.42311;

        $lat         = $request->param('lat')?:23.085747;

        $data = Db::name('new_house')->field('id house_id,title,intro,thumb_img,labels,min_area,max_area,unit_price')
            ->where('off',1)
            ->orderRaw('ACOS(SIN(('.$lat.' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$lat.' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS(('.$lng.' * 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc')
            ->limit(10)->cache(20)->select();


        if($data){
            foreach($data as &$row){

                $row['labels']  = Db::name('house_label')->field('tag_name,color_type')->whereIn('id',$row['labels'])->cache(20)->select();
            }
        }

        $res['img_prefix']  = config('api.oss_img_path');
        $res['poster_img'] = Db::name('house_module')->where('type',4)->cache(20)->value('poster_img');
        $res['house_list']  = $data;


        return msg(200,'success',$res);

    }


    /**
     * 获取出租房推荐页列表
     * @param lng 经度
     * @param lat 维度
     */
    public function getRentHouseRecommend (Request $request) {


        $lng         = $request->param('lng')?:114.42311;

        $lat         = $request->param('lat')?:23.085747;

        $data = Db::name('rent_house')->field('id house_id,title,total_area,floors,labels,direction,floor_type,charter_money,thumb_img')
            ->where('off',1)
            ->orderRaw('ACOS(SIN(('.$lat.' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$lat.' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS(('.$lng.' * 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc')
            ->limit(10)->cache(20)->select();


        if($data){
            foreach($data as &$row){
                $row['direction'] = config('api.aspect')[$row['direction']-1]['aspect_name'];
                $row['floor_type'] = ApiModel::$floor_types[$row['floor_type']];
                $row['intro'] = $row['total_area'].'㎡/'.$row['direction'].'/'.$row['floor_type'].'/共'.$row['floors'].'层';
                unset($row['direction']);
                unset($row['floor_type']);
                unset($row['total_area']);
                unset($row['floors']);
                $row['labels']  = Db::name('house_label')->field('tag_name,color_type')->whereIn('id',$row['labels'])->cache(20)->select();
            }
        }

        $res['img_prefix']  = config('api.oss_img_path');
        $res['poster_img'] = Db::name('house_module')->where('type',5)->cache(20)->value('poster_img');

        $res['house_list']  = $data;

        return msg(200,'success',$res);

    }


    /**
     * 获取租房房源列表
     * @param lng           经度
     * @param lat           纬度
     * @param page          页码
     * @param adcode        行政区编码 （区域id）
     * @param place_code    地方编码
     * @param min_price     最低价格
     * @param max_price     最高价格
     * @param min_area      最小面积
     * @param max_area      最大面积
     * @param rent_type     租房类型 1整租 2合租
     * @param min_age       最小楼龄
     * @param max_age       最大楼龄
     * @param tag_ids       标签ids
     * @param fitment_type  装修类型
     * @param seach_text    搜索内容
     */
    public function getRentHouse(Request $request){

        $inputData   = $request->param();

        $lng         = $request->param('lng')?:114.42311;
        $lat         = $request->param('lat')?:23.085747;

        $page        = $request->param('page')?:1;
        $pageSize    = 15;
        $start       = ($page-1)*$pageSize;

        $where       = [];

        //区域条件
        if(!empty($inputData['place_code'])) {
            //片区
            $where[] =  ['area_id', '=',$inputData['place_code']];

        }else if(!empty($inputData['adcode'])){

            //行政区
            $pids = Db::name('region')->field('id')->where('pid',$inputData['adcode'])->cache(20)->select();


//            $where[] = ['area_id','in',"select id from region where pid ={$inputData['adcode']}"];
            if($pids){
                $ids = '';
                foreach($pids as $v){
                    $ids .= ','.$v['id'];
                }

                $ids = ltrim($ids,',');

                $where[]=['area_id','in',$ids];
            }

        }
        $where2 = 'off=1';

        //价格区间
        if(!empty($inputData['price_type'])){

            $price_range = config('api.rent_price_range')[$inputData['price_type']-1];
            $where[] = ['charter_money','>=',$price_range['min']] ;

            if($price_range['max']>0){
                $where[] = ['charter_money','<=',$price_range['max']] ;

            }
        }


        //面积区间
        if(!empty($inputData['area_type'])){

            $area_range = config('api.area_range')[$inputData['area_type']-1];

            $where[] = ['total_area','>=',$area_range['min']] ;
            if($area_range['max']>0){
                $where[] = ['total_area','<=',$area_range['max']] ;
            }
        }


        //楼龄区间
        if(!empty($inputData['age_type'])){

            $age_range = config('api.house_age_range')[$inputData['age_type']-1];

            $where[] = ['house_age','>=',$age_range['min']] ;
            if($age_range['max']>0){
                $where[] = ['house_age','<=',$age_range['max']] ;
            }
        }


        if(!empty($inputData['fitment_type']))      $where[] = ['fitment_case','<=',$inputData['fitment_type']] ;   //装修情况

        if(!empty($inputData['rent_type']))         $where[] = ['rent_type','<=',$inputData['rent_type']] ;   //装修情况

        if(!empty($inputData['tag_ids'])) {
            //标签
            $tags = explode(',',$inputData['tag_ids']);

            if($tags){
                $where2 .=' and (';
                foreach($tags as $v) {
                    $where2 .= " FIND_IN_SET($v,labels) or";
                }
                $where2 = rtrim($where2,'or').')';
            }
        }


        if(!empty($inputData['seach_text'])) {
            $data = Db::name('rent_house')->field('id house_id,title,total_area,floors,labels,direction,floor_type,charter_money,thumb_img')
                ->where('off',1)
                ->where('title|address|uptown','like',"%{$inputData['seach_text']}%")
                ->orderRaw('ACOS(SIN(('.$lat.' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$lat.' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS(('.$lng.' * 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc')
                ->limit($start,$pageSize)->cache(20)->select();
        }else{

//            dump($where);
            $data = Db::name('rent_house')->field('id house_id,title,total_area,floors,labels,direction,floor_type,charter_money,thumb_img')
                ->where($where)->where($where2)
                ->orderRaw('ACOS(SIN(('.$lat.' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$lat.' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS(('.$lng.' * 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc')
                ->limit($start,$pageSize)->cache(20)->select();
        }



        if($data){


            foreach($data as &$row){

                $row['direction'] = config('api.aspect')[$row['direction']-1]['aspect_name'];
                $row['floor_type'] = ApiModel::$floor_types[$row['floor_type']];
                $row['intro'] = $row['total_area'].'㎡/'.$row['direction'].'/'.$row['floor_type'].'/共'.$row['floors'].'层';
                unset($row['direction']);
                unset($row['floor_type']);
                unset($row['total_area']);
                unset($row['floors']);
                $row['labels']  = Db::name('house_label')->field('tag_name,color_type')->whereIn('id',$row['labels'])->cache(20)->select();
            }
        }

        $res['img_prefix']  = config('api.oss_img_path');
        $res['house_list']  = $data;
        $res['next_page']   = $page+1;

        return msg(200,'success',$res);

    }


    /**
     * 获取租房详情
     * @param  house_id  房源id
     */
    public function getRentHouseDetails(Request $request){

        $house_id = $request->param('house_id');

        if(!$house_id) return msg(101,'参数有误');

        $details = Db::name('rent_house a')
            ->join('house_broker b','a.broker_id=b.id','left')
            ->field('a.title,a.viewpager,a.charter_money,a.room_num,a.lobby_num,a.uptown,a.total_area,a.labels,a.rent_way,a.allocation,a.floor_type,a.place_floor,a.direction,a.address,a.fitment_case,a.use_type,a.coding,a.lng,a.lat,a.look_at_house,a.check_in_time,a.floor_ratio,a.heating,a.broker_id,b.broker_phone,b.broker_name,b.hx_username broker_hx_name,b.avatar broker_avatar')
            ->where('a.id',$house_id)->where('a.off',1)->cache(20)->find();

        if($details){

            $details['img_prefix'] =  config('api.oss_img_path');

            $details['viewpager']  =  json_decode($details['viewpager'],true);

            $config = config('api.numberToChinese');

            $details['direction'] = config('api.aspect')[$details['direction']-1]['aspect_name'];

            $details['house_type'] =  $details['room_num'].'房'.$details['lobby_num'].'厅';

            $details['heating']  =config('api.heating')[$details['heating']];

            $details['floor_ratio'] = '一梯'.config('api.numberToChinese')[$details['floor_ratio']].'户';

            $details['labels'] =  Db::name('house_label')->field('tag_name,color_type')->whereIn('id',$details['labels'])->cache(20)->select();

            $details['floor_type'] = config('api.floor_types')[$details['floor_type']-1]['title'];

            $details['use_type'] = config('api.purpose')[$details['use_type']-1]['title'];

            $details['fitment_case']  = config('api.fitment_case')[$details['fitment_case']-1]['title'];


            $details['intro'] = $details['charter_money'].'元/月 '.$details['house_type'].'/'.$details['total_area'].'m² ';


            $nearby_house = Db::name('rent_house')->field('id house_id,title,thumb_img,charter_money,room_num,lobby_num,total_area,direction')
                ->where('off',1)
                ->orderRaw('ACOS(SIN(('.$details['lat'].' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$details['lat'].' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS(('.$details['lng'].' * 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc')
                ->limit(5)->cache(20)->select();

            if($nearby_house){
                foreach($nearby_house as $k =>&$v){
                    $v['direction'] = config('api.aspect')[$v['direction']-1]['aspect_name'];

                    $v['intro'] = $v['room_num'].'室'.$v['lobby_num'].'厅'.'/'.$v['total_area'].'m²'.'/'.$v['direction'];
                    unset($v['room_num']);
                    unset($v['lobby_num']);
                    unset($v['total_area']);
                    unset($v['direction']);
                }
            }

            $uid = $request->param('uid');

            //关注状态
            if(empty($uid)){
                $details['collect_status'] = 2;

            }else{

                $coll = Db::name('app_user_collect')->where(['uid'=>$uid,'house_id'=>$house_id,'type'=>3])->find();

                $details['collect_status'] = empty($coll)?2:1;

            }

            unset($details['room_num']);
            unset($details['lobby_num']);

            $details['nearby_house'] = $nearby_house;
            return msg(200,'success',$details);

        }else{
            return msg(100,'暂无数据');
        }

    }

    /**
     * 获取店铺列表
     * @param lng            经度
     * @param lat            纬度
     * @param page           页码
     * @param store_type     店铺类型   1家居  2装修
     * @param attr_type      属性
     * @param place_code     片区编码
     * @param adcode         行政区编码
     * @param seach_text     搜索内容
     */
    public function getFurnitureStore(Request $request) {

        $inputData   = $request->param();

        $lng         = $request->param('lng')?:114.42311;
        $lat         = $request->param('lat')?:23.085747;

        $page        = $request->param('page')?:1;
        $pageSize    = 15;
        $start       = ($page-1)*$pageSize;
        $type        = empty($inputData['store_type'])?1:$inputData['store_type'];
        $where       = [];



        //区域条件
        if(!empty($inputData['place_code'])) {
            //片区
            $where[] =  ['a.area_id', '=',$inputData['place_code']];

        }else if(!empty($inputData['adcode'])){

            //行政区
            $pids = Db::name('region')->field('id')->where('pid',$inputData['adcode'])->cache(20)->select();

//            $where[] = ['area_id','in',"select id from region where pid ={$inputData['adcode']}"];
            if($pids){
                $ids = '';
                foreach($pids as $v){
                    $ids .= ','.$v['id'];
                }

                $ids = ltrim($ids,',');

                $where[]=['a.area_id','in',$ids];
            }

        }

        if(!empty($inputData['min_price']))    $where[] = ['a.price','>=',$inputData['min_price']] ;     //最低价格

        if(!empty($inputData['max_price']))    $where[] = ['a.price','<=',$inputData['max_price']] ;     //最高价格

        $where2 = 'off=1 and type='.$type;

        if(!empty($inputData['attr_type']))   $where2.=' and  FIND_IN_SET('.$inputData['attr_type'].',a.types)';     //类型


        //价格区间
        if (!empty($inputData['price_type'])) {


            if($type==1){
                $price_range = config('api.furniture_store_price_range')[$inputData['price_type'] - 1];

            }else{
                $price_range = config('api.fitment_store_price_range')[$inputData['price_type'] - 1];

            }

            $where[] = ['price', '>=', $price_range['min']];
            if ($price_range['max'] > 0) {
                $where[] = ['price', '<=', $price_range['max']];
            }
        }


        if(!empty($inputData['seach_text'])){
            $data = Db::name('furniture_store a')->field('a.id store_id,a.title,a.thumb_img,a.types,a.area_id')
                ->where('a.title|a.address','like',"%{$inputData['seach_text']}%")
                ->where($where2)
                ->orderRaw('ACOS(SIN(('.$lat.' * 3.1415) / 180 ) *SIN((a.lat * 3.1415) / 180 ) +COS(('.$lat.' * 3.1415) / 180 ) * COS((a.lat * 3.1415) / 180 ) *COS(('.$lng.' * 3.1415) / 180 - (a.lng * 3.1415) / 180 ) ) * 6380 asc')
                ->limit($start,$pageSize)->cache(20)->select();
        }else{
            $data = Db::name('furniture_store a')->field('a.id store_id,a.title,a.thumb_img,a.types,a.area_id')
                ->where($where)->where($where2)
                ->orderRaw('ACOS(SIN(('.$lat.' * 3.1415) / 180 ) *SIN((a.lat * 3.1415) / 180 ) +COS(('.$lat.' * 3.1415) / 180 ) * COS((a.lat * 3.1415) / 180 ) *COS(('.$lng.' * 3.1415) / 180 - (a.lng * 3.1415) / 180 ) ) * 6380 asc')
                ->limit($start,$pageSize)->cache(20)->select();
        }

        if($data){

            $configTypes = config('api.furniture_store_attrs');

            $regionArr = [];
            foreach($data as $k => &$v){

                if(!empty($regionArr[$v['area_id']])){
                    $v['region'] = $regionArr[$v['area_id']];
                }else{
                    $regionName = Db::name('region')->where("id = (select pid from region where id= {$v['area_id']})")->cache(60)->value('name');
                    $v['region'] = $regionArr[$v['area_id']] = $regionName;

                }

                unset($v['area_id']);
                if($v['types']){
                    $typeArr = explode(',',$v['types']);
                    if($typeArr){
                        $v['types'] = '';
                        foreach($typeArr as $vv){
                            $v['types'] .= $configTypes[$vv-1]['title'].' ';
                        }
                    }
                }
            }
        }

        $res['img_prefix']  = config('api.oss_img_path');
        $res['store_list']  = $data;
        $res['next_page']   = $page+1;

        return msg(200,'success',$res);
    }

    /**
     * 获取店铺详情
     * @param store_id  店铺id
     */
    public function getFurnitureStoreDetails(Request $request){

        $id = $request->param('store_id');

        if(!$id) return msg(101,'参数有误');


        $details = Db::name('furniture_store a')->join('house_broker b','a.broker_id=b.id','left')
                ->field('a.title,a.poster_img,a.address,a.business_time,a.pledge,a.description,a.lng,a.lat,b.broker_phone')
                ->where('a.id',$id)->where('off',1)->cache(20)->find();

        //附近店铺
        $nearby_store = Db::name('furniture_store')->field('thumb_img,title,area_id region,id store_id')
                ->where('off',1)
                ->orderRaw('ACOS(SIN(('.$details['lat'].' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$details['lat'].' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS(('.$details['lng'].' * 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc')
                ->limit(5)->cache(20)->select();


         if($nearby_store){
             $regionArr = [];
             foreach($nearby_store as $k=>&$v){

                 if(!empty($regionArr[$v['region']])){
                     $v['region'] = $regionArr[$v['region']];
                 }else{
                     $regionName = Db::name('region')->where("id = (select pid from region where id= {$v['region']})")->value('name');
                     $v['region'] = $regionArr[$v['region']] = $regionName;
                 }
             }
         }


        $uid = $request->param('uid');


        //关注状态
        if(empty($uid)){
            $details['collect_status'] = 2;

        }else{

            $coll = Db::name('app_user_collect')->where(['uid'=>$uid,'house_id'=>$id,'type'=>['>',3]])->find();

            $details['collect_status'] = empty($coll)?2:1;

        }


        unset($details['lng']);
        unset($details['lat']);
        $details['img_prefix']  = config('api.oss_img_path');
        $details['nearby_store'] = $nearby_store;
         return msg(200,'success',$details);

    }


    /**
     * 获取海外首页
     */
    public function getOverseasIndex(){

        $poster_img = Db::name('house_module')->where('type',8)->value('poster_img');

        $regions = Db::name('overseas_region')->where('pid',0)->field('id region_id,shortname,thumb_img')->order('id','desc')->limit(15)->select();

        $advisers = Db::name('overseas_adviser')->field('adviser_name,avatar,intro,phone')->order('id','desc')->limit(5)->select();


        $res = array(
            'img_prefix'=>config('api.oss_img_path'),
            'poster_img'=>$poster_img,
            'regions'   =>$regions,
            'advisers'  =>$advisers
        );

        return msg(200,'success',$res);

    }


    /**
     * 地图找房
     * @param  lng          经度
     * @param  lat          维度
     * @param  adcode       行政区代码
     * @param  area_range   面积范围  公里数
     * @param  house_type   房源类型  1新房 2二手房  3租房
     */
    public function mapGetHouse(Request $request){

        $params = $request->param();

        if(empty($params['lng']) || empty($params['lat'])){
            return msg(101,'请上传坐标');
        }

        $type = !empty($params['house_type'])?$params['house_type']:1;
        $range = !empty($params['area_range'])?$params['area_range']:5;
        $lng = $params['lng'];
        $lat = $params['lat'];


        //新房、二手房 、租房
        switch ($type){
            case 1:
                $table = 'new_house';
                $price = 'unit_price';
                break;
            case 2:
                $table = 'resold_house';
                $price = 'unit_price';
                break;
            case 3:
                $table = 'rent_house';
                $price = 'charter_money';
                break;
        }

        if($range < 10){  //附近房源

            $scope = ApiModel::calcScope($lng,$lat,$range*1000); //计算范围

            $data = Db::name($table)
                                ->field("id house_id,uptown title,$price intro,lng,lat")
                                ->whereBetween('lng',"{$scope['minLng']},{$scope['maxLng']}")
                                ->whereBetween('lat',"{$scope['minLat']},{$scope['maxLat']}")
                                ->where('off',1)->cache(20)->select();

            if($data){
                foreach($data as &$v){
                    switch ($type){
                        case 1:
                            $v['intro'] = '均价'.$v['intro'].'元/平';
                            break;
                        case 2:
                            $v['intro'] = $v['intro'].'元/平';
                            break;
                        case 3:
                            $v['intro'] = $v['intro'].'元/月';
                            break;
                    }
                }
            }

        }else{
            if(empty($params['adcode'])) return msg(101,'请提交adcode参数');

            //统计当前城市区域房源数量
//            $city_id = Db::name('region a')->join('region b','b.id=a.pid')
//                    ->where('a.id',$params['adcode'])->cache(30)->value('b.pid');

            $data = Db::name('region')->field('id house_id,name title,house_num intro,lng,lat')
                ->where("pid = (select b.id from region a join region b on b.id=a.pid where a.id={$params['adcode']} )")->cache(30)->select();

            if(!$data) return msg(101,'该编码无法获取位置信息');

            foreach($data as &$v){
               $v['intro'] = $v['intro'].'套';
            }


        }
        return msg(200,'success',$data);

    }



    /**
     * 地图找房中房源详情
     * @param  house_id
     * @house_type  1新房  2二手房  3租房
     */

    public function getMapHouseDetails(Request $request){

        $id = $request->param('house_id');
        $type = $request->param('house_type');


        if(empty($id) || empty($type)) return msg(101,'缺少参数');


        switch($type){
            case 1:
                $house = Db::name('new_house')->field('id house_id,title,labels,thumb_img,unit_price')->where('id',$id)->cache(10)->find();

                if($house){
                   $house['intro'] = '均价：'.$house['unit_price'].'元m²';
                   unset($house['unit_price']);
                }

                break;
            case 2:
                $house = Db::name('resold_house')->field('id house_id,title,labels,thumb_img,total_price,total_area')->where('id',$id)->cache(10)->find();

                if($house){
                    $house['intro'] = '售价：'.$house['total_price'].'万元  '.'面积：'.$house['total_area'].'m²';
                    unset($house['unit_price']);
                    unset($house['total_area']);
                }

                break;
            case 3:
                $house = Db::name('rent_house')->field('id house_id,title,labels,thumb_img,charter_money')->cache(10)->where('id',$id)->find();

                if($house){
                    $house['intro'] = $house['charter_money'].'元/月';
                    unset($house['charter_money']);
                }

                break;

        }

        if(!empty($house)){

            $house['labels'] = Db::name('house_label')->field('tag_name,color_type')->whereIn('id',$house['labels'])->cache(10)->select();
            $house['thumb_img'] = config('api.oss_img_path').$house['thumb_img'];
            return msg(200,'fail',$house);


        }else{
            return msg(200,'fail',(object)[]);

        }

    }


    /**
     * 获取海外房源列表

     * @param page          页码
     * @param adcode        行政区编码 （区域id）
     * @param price_type    价格类型
     * @param house_type    房型
     * @param area_type     面积类型
     * @param aspect_id     朝向标记
     * @param floor_type    楼层类型
     * @param purpose_id    用途标记
     * @param tag_ids       标签ids
     * @param seach_text    搜索内容
     */
    public function getOverseasHouse(Request $request){

        $inputData   = $request->param();

//        if(!$inputData) return msg(101,'请上传参数');


        $page        = $request->param('page')?:1;
        $pageSize    = 15;
        $start       = ($page-1)*$pageSize;

        $where       = [];


        //区域条件
        if(!empty($inputData['adcode'])) {

            $regions = Db::name('overseas_region')->field('id')->where('pid',$inputData['adcode'])->select();

            if($regions){
               $ids = '';
               foreach($regions as $v){
                   $ids.= $v['id'].',';
               }

               $ids = rtrim($ids,',');

                $where[] = ['area_id','in',$ids];
            }else{
                $where[] =  ['area_id', '=',$inputData['adcode']];

            }

        }

        //价格区间
        if(!empty($inputData['price_type'])){

            $price_range = config('api.price_range')[$inputData['price_type']-1];

            $where[] = ['total_price','>=',$price_range['min']] ;
            if($price_range['max']>0){
                $where[] = ['total_price','<=',$price_range['max']] ;
            }
        }


        //面积区间
        if(!empty($inputData['area_type'])){

            $area_range = config('api.area_range')[$inputData['area_type']-1];

            $where[] = ['total_area','>=',$area_range['min']] ;
            if($area_range['max']>0){
                $where[] = ['total_area','<=',$area_range['max']] ;
            }
        }

        if(!empty($inputData['house_type']))  $where[] = ['room_num','in',$inputData['house_type']] ;    //房型


        if(!empty($inputData['aspect_id']))   $where[] = ['direction','=',$inputData['aspect_id']] ;    //朝向

        if(!empty($inputData['floor_type']))  $where[] = ['floor_type','=',$inputData['floor_type']] ;  //楼层类型

        if(!empty($inputData['purpose_id']))  $where[] = ['use_type','=',$inputData['purpose_id']] ;    //用途


        $where2 = 'off=1';
        if(!empty($inputData['tag_ids'])) {
            //标签
            $tags = explode(',',$inputData['tag_ids']);

            if($tags){
                $where2 .=' and (';
                foreach($tags as $v) {
                    $where2 .= " FIND_IN_SET($v,labels) or";
                }
                $where2 = rtrim($where2,'or').')';
            }
        }



        if(!empty($inputData['seach_text'])) {
            $data = Db::name('overseas_house')->field('id house_id,title,thumb_img,labels,total_area,direction,floor_type,floors,total_price,unit_price')
                ->where('title|address|uptown','like',"%{$inputData['seach_text']}%")
                ->where('off',1)->order('id desc')
                ->limit($start,$pageSize)->cache(20)->select();
        }else{
            $data = Db::name('overseas_house')->field('id house_id,title,thumb_img,use_type,total_area,address,total_price')
                ->where($where)->where($where2)
                ->order('id desc')
                ->limit($start,$pageSize)->cache(20)->select();
        }


        if($data){
            foreach($data as &$row){
                $row['use_type'] = config('api.overseas_purpose')[$row['use_type']]['title'];
            }
        }

        $res['img_prefix']  = config('api.oss_img_path');
        $res['house_list']  = $data;
        $res['next_page']   = $page+1;

        return msg(200,'success',$res);

    }


    /**
     * 获取海外房源详情
     * @param  house_id  房源id
     */
    public function getOverseasHouseDetails(Request $request){

        $house_id = $request->param('house_id');

        if(!$house_id) return msg(101,'参数有误');

        $details = Db::name('overseas_house a')
            ->join('house_broker b','a.broker_id=b.id','left')
            ->field('a.title,a.description,a.labels,a.total_price,a.total_area,a.direction,a.floor_type,a.floors,a.unit_price,a.address,a.uptown,a.viewpager,a.durable_years,a.coding,a.budget,a.usable_area,a.structure,a.floor_ratio,a.heating,a.transaction_type,a.property_right_type,a.pledge,a.house_cert,a.soil_years,a.time,a.room_num,a.lobby_num,a.carport_type,a.use_type,a.fitment_case,a.broker_id,b.broker_phone,b.broker_name,b.hx_username broker_hx_name,b.avatar broker_avatar')
            ->where('a.id',$house_id)->where('a.off',1)->cache(20)->find();

        if($details){

            $details['img_prefix'] =  config('api.oss_img_path');

            $details['viewpager']  =  json_decode($details['viewpager'],true);

            $config = config('api.numberToChinese');

            $details['direction'] = config('api.aspect')[$details['direction']-1]['aspect_name'];

            $details['house_type'] =  $config[$details['room_num']].'房'.$config[$details['lobby_num']].'厅';

            $details['structure'] =  $details['structure']?:'暂无信息';

            $details['heating']  =config('api.heating')[$details['heating']];

            $details['house_cert']  = $details['house_cert']?:'';

            $details['carport_type']  = config('api.carport_types')[ $details['carport_type']];

            $details['floor_ratio'] = '一梯'.config('api.numberToChinese')[$details['floor_ratio']].'户';
            $details['labels'] =  Db::name('house_label')->field('tag_name,color_type')->whereIn('id',$details['labels'])->cache(20)->select();

            $details['floor_type'] = config('api.floor_types')[$details['floor_type']-1]['title'];

            $details['use_type'] = config('api.overseas_purpose')[$details['use_type']-1]['title'];

            $details['fitment_case']  = config('api.fitment_case')[$details['fitment_case']-1]['title'];

            $details['transaction_type']  = config('api.transaction_types')[$details['transaction_type']];

            $details['property_right_type']  = config('api.property_right_types')[$details['property_right_type']];

            $details['intro'] = $details['total_price'].'万/'.$details['total_area'].'m²/'.$details['house_type'];


            $details['nearby_house'] = Db::name('overseas_house')->field('id house_id,title,thumb_img,total_price,unit_price')
                ->where('off',1)
                ->order('id desc')
                ->limit(5)->cache(20)->select();
            unset($details['room_num']);
            unset($details['lobby_num']);

            return msg(200,'success',$details);

        }else{
            return msg(100,'暂无数据');

        }

    }


    /**
     * 获取所有城市
     */
    public function getAllCity(){
        $citys = Db::name('region')->field('shortname,lng,lat,initial')
            ->where('initial <> "" ')->order('initial asc')->select();

        $data = array();
        foreach($citys as $v){
            $data[$v['initial']][]=$v;
        }

        $list = [];
        foreach($data as $k=>$v){
           $list[] = array(
               'city_prefix'=>$k,
               'city_list'=>$v
           );
        }

        return msg(200,'success',$list);
    }


    //发送短信
    public function testSendSms(){
        $send = send_sms('13068211710', 1, ['code'=>'4678']);

        dump($send);
    }

    public function test()
    {
        $con = [
            [114.42311, 23.085747], [114.40877, 23.072474], [114.38973, 23.109491], [114.4199, 23.105362],
            [114.38784, 23.078022], [114.41971, 23.073387], [114.37219, 23.035906], [114.31879, 23.00818],
            [114.52466, 23.150635], [114.42027, 23.170792], [114.45874, 23.177395], [114.45289, 22.987307],
            [114.196655, 23.082232], [114.23843, 22.975706], [114.48172, 23.062883], [114.61613, 23.168669],
            [114.528404, 23.362764], [114.3003, 23.03519], [114.41398, 23.079884],
        ];

        die;
        $len = count($con);

        $data = Db::name('resold_house')->field('id')->select();

        foreach ($data as $k => $v) {
            $rand = rand(0, $len - 1);

            $res = Db::name('resold_house')->where('id', $v['id'])->update(['lng' => $con[$rand][0], 'lat' => $con[$rand][1]]);

            dump($res);
        }

    }
}


